<template>
  <el-row>
    <el-col :span="20" :offset="2">
      <el-form ref="userForm" :model="userForm" :rules="userRules" label-width="80px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="account">
          <el-input v-model="userForm.account"></el-input>
        </el-form-item>
        <el-form-item label="密　码" prop="password">
          <el-input v-model="userForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login('userForm')">登录</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>


</template>

<script>
import router from '../router';
export default {
  name: 'Login',
  data() {
    return {
      userForm: {
        account: '',
        password: ''
      },
      userRules: {
        account: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }, ]
      }
    }
  },
  methods: {
    login(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios.post("http://127.0.0.1:8085/user/login",this.userForm)
            .then(res => {
              const resData = res;
              console.log(resData);
              const token = resData.token;
              const account = resData.account;
              const nickname = resData.nickname;
              localStorage.setItem('token',token);
              console.log('Token stored in localStorage.');
              document.cookie = `token=${token}; expires=${new Date(new Date().getTime() + 24 * 60 * 60 * 1000)}; path=/`;
              document.cookie = `account=${account}; expires=${new Date(new Date().getTime() + 24 * 60 * 60 * 1000)}; path=/`;
              document.cookie = `nickname=${nickname}; expires=${new Date(new Date().getTime() + 24 * 60 * 60 * 1000)}; path=/`;
              console.log('Token stored in cookie.');
              //跳转主页
              location.href='/'

            })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }

  },

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
